﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using StyleMVVM.DependencyInjection;
using StyleMVVM.DependencyInjection.Impl;

namespace StyleMVVM.MVC.Extensions
{
	[Export(typeof(IViewPageActivator))]
	public class ViewPageActivator : IViewPageActivator
	{
		private IDependencyInjectionContainer container;

		[ImportConstructor]
		public ViewPageActivator(IDependencyInjectionContainer container)
		{
			this.container = container;
		}

		public object Create(ControllerContext controllerContext, Type type)
		{
			// We use the GUID because when ASP.Net compilier re-compile it uses the same type name but different GUID
			object returnObject = container.Locate(type.GUID.ToString());

			if (returnObject == null)
			{
				AttributedExportStrategy exportStrategy = new AttributedExportStrategy(new[] { type.GUID.ToString() }, type);

				container.AddStrategy(exportStrategy);

				returnObject = exportStrategy.Activate(container.CreateInjectionContext(), null);
			}

			return returnObject;
		}
	}
}